package handler

import (
	"car-rental-08-14/api/request"
	"car-rental-08-14/internal/dao"
	"car-rental-08-14/internal/model"
	"car-rental-08-14/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	err := dao.GetValeInfo(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    "",
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		Status:   1,
	}

	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.CreatedAt,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err := dao.GetValeInfo(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "登录失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登录成功",
		"data":    "",
	})
}

func GetListByStatusUser(c *gin.Context) {
	var req request.GetListByStatusUserForm
	var user []model.User

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}
	err := dao.GetTableInfo(&model.User{Status: req.Status}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "获取失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "获取成功",
		"data":    user,
	})
}

func FreezeUser(c *gin.Context) {
	var user model.User

	//1 正常 2 冻结
	user.Status = 2

	err := dao.UpdatedInfo(&user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "冻结失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "冻结成功",
		"data":    user,
	})
}
